<?php namespace Admin\Controller;

//城市控制器
class CityController extends CommonController{
	//存放模型对象
	private $cityModel;
	public function __auto(){
		$this->cityModel=new \Common\Model\City;
	}

	//城市列表
	public function index(){
		//获取所有数据
		$data=$this->cityModel->orderBy('city_sort','ASC')->get();
		//判断分类是否为空
		if (!$data) View::error('请先添加城市',U('addCity'));
		//将数据转为树状图
		$dataTree=Data::tree($data,'city_name','city_id','city_pid');
		View::with('dataTree',$dataTree)->make();
	}

	//添加城市
	public function addCity(){
		if (IS_POST) {
			if (!$this->cityModel->store()) View::error($this->cityModel->getError());
			View::success('添加成功',U('index'));
		}
		View::make();
	}

	//添加地区
	public function addArea(){
		if (IS_POST) {
			if (!$this->cityModel->store()) View::error($this->cityModel->getError());
			View::success('添加成功',U('index'));
		}
		//获得该条数据
		$city_id=Q('get.city_id',0,'intval');
		$city=$this->cityModel->where("city_id=$city_id")->find();
		View::with('city',$city)->make();
	}

	//删除城市或地区
	public function del(){
		//获得该条数据
		$city_id=Q('get.city_id',0,'intval');
		//如果分类下有子分类
		$city_pid=$this->cityModel->where("city_id=$city_id")->pluck('city_pid');
		$this->cityModel->where("city_pid=$city_id")->update(['city_pid'=>$city_pid]);
		//删除分类
		$this->cityModel->where("city_id=$city_id")->delete();
		View::success('删除成功');
	}

	//编辑城市
	public function edit(){
		if (IS_POST) {
			if (!$this->cityModel->edit()) View::error($this->cityModel->getError());
			View::success('修改成功',U('index'));
		}
		//获得该条数据
		$city_id=Q('get.city_id',0,'intval');
		$data=$this->cityModel->where("city_id=$city_id")->find();
		View::with('data',$data);
		//获得除了自己和自己子集的树桩分类
		$dataTree=Data::tree($this->cityModel->notMy($city_id),'city_name','city_id','city_pid');
		View::with('dataTree',$dataTree)->make();
	}


}